const fs = require('fs')
const path = require('path')
const puppeteer = require('../')
const base64src = new Buffer(fs.readFileSync('images/mouse.png')).toString('base64')

async function main() {
  const browser = await puppeteer.launch({ headless: false })
  const page = await browser.newPage()
  const targetUrl = 'https://reg.taobao.com/member/reg/fill_mobile.htm'
  const executablePath = 'E:\\softwares\\chrome-win32\\chrome.exe'
  await page.goto(targetUrl, { waitUntil: 'networkidle', executablePath })
  await page.evaluate(addMouse, base64src)
  await page.evaluate(hideDialog)
  await page.waitFor('#J_AgreementBtn')
  await page.click('#J_AgreementBtn')
  const mouse = page.mouse
  const dragOperation = async () => {
    console.log('drag operation')
    const { fromX, y, toX } = await page.evaluate(getTargetPosition)
    await mouse.click(fromX, y, {
      delay: 100
    })
    await mouse.down()
    await mouse.move(toX, y, {
      steps: 30
    })
    await mouse.up()
  }
  await dragOperation()
  await page.waitFor(200)
  const hasErrorSelector = '#register_no_captcha a'
  if (await page.evaluate(notPass, hasErrorSelector)) {
    await page.waitForSelector(hasErrorSelector)
    await page.waitFor(500)
    await page.click(hasErrorSelector)
    await dragOperation()
  }
  await page.evaluate(removeListener)
}

main()

function addMouse(base64src) {
  const defaultStyle = {
    position: 'fixed',
    top: 0,
    left: 0,
    width: '20px',
    height: '20px',
    zIndex: 999,
  }
  const elem = document.createElement('div')
  const img = document.createElement('img')
  img.src = `data:image/png;base64,${base64src}`
  img.style.width = '100%'
  img.style.height = '100%'
  elem.appendChild(img)
  Object.assign(elem.style, defaultStyle)
  document.body.appendChild(elem)
  window.handleMouseMove = (event) => {
    Object.assign(elem.style, {
      top: `${event.clientY + 1}px`,
      left: `${event.clientX + 1}px`,
    })
  }
  window.addEventListener('mousemove', window.handleMouseMove)
}

function removeListener() {
  window.removeEventListener('mousemove', window.handleMouseMove)
}

function hideDialog() {
  const dialog = document.getElementById('J_xiaomi_dialog')
  Object.assign(dialog.style, { display: 'none' })
}

function getTargetPosition() {
  const target = document.getElementById('nc_1__scale_text')
  const { x, y, right } = target.getBoundingClientRect()
  return {
    fromX: x,
    y,
    toX: right,
  }
}

function notPass(selector) {
  return document.querySelector(selector)
}